<?php

namespace Service\Providers;

use http\Params;
use JsonException;
use Service\Model\Model;

class TokenAuthenticateProviders
{
    private static $encryptKey = "testKey";

    public static function createToken($payload): string
    {
        if ($payload instanceof Model) {
            $json = $payload->to_json();
        }
        else {
            $json = json_encode($payload);
        }
        return TokenAuthenticateProviders::encryptData($json);
    }

    public static function getTokenPayload($payload)
    {
        try {
            return json_decode(TokenAuthenticateProviders::decryptData($payload), true, 512, JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
        }
        return null;
    }

    private static function encryptData($data): string
    {
        $iv = substr(md5(uniqid()), 0, 16);
        return base64_encode($iv . openssl_encrypt($data, 'aes-256-cbc', TokenAuthenticateProviders::$encryptKey, 0, $iv));
    }

    private static function decryptData($eData)
    {
        $eData = base64_decode($eData);
        $iv = substr($eData, 0, 16);
        return openssl_decrypt(substr($eData, 16), 'aes-256-cbc', TokenAuthenticateProviders::$encryptKey, 0, $iv);
    }

}